import {defineModel, getCurrentInstance, ref} from "vue";
import {ElMessage} from "element-plus";
import {commonQuery} from "../api/index.js";
function commonHook({
    baseUrl = '',
    rowForm = ref(),
    _data = defineModel({default: []}),
    queryParams = ref({}),
    selection = ref([]),
    orderBy = ref(null),
    isPage = true,
    pagination = ref({
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        total: 0,
    }),
    emptyData = ref({}),
    conditions = [],
    getQueryOptions = ()=> {
        let _query, _pagination, _orderBy
        if (queryParams.value && Object.keys(queryParams.value).length) {
            const children = []
            for (const key in queryParams.value) {
                if (queryParams.value[key] || queryParams.value[key] === 0) {
                    children.push({queryKey: key, queryValue: queryParams.value[key]})
                }
            }
            if (children.length) _query = {children}
        }
        if (conditions && conditions.length) {
            if (!_query) {
                _query = {children: conditions}
            } else {
                _query.children.push(...conditions)
            }
        }
        if (isPage && pagination.value && Object.keys(pagination.value).length) {
            _pagination = {
                currentPage: pagination.value.currentPage,
                pageSize: pagination.value.pageSize,
            }
        }
        if (orderBy.value) {
            _orderBy = orderBy.value
        }
        return {query: _query, pagination: _pagination, orderBy: _orderBy}
    },
    loading = ref(false),
    actionsFormVisible = ref({}),
    isSub=false,
    columns=ref([]),
    simpleTitle = '',
}) {
    const commonQueryFn = commonQuery(baseUrl)
    const {getById,empty,list,page,save,update,saveOrUpdate,removeByIds,importTemplate,importData,downBinary} = commonQueryFn

    async function search() {
        if (isSub) {
            return
        }
        loading.value = true
        let response = isPage ? await page(getQueryOptions()) : await list(getQueryOptions())
        const {success, msg, data} = response
        const _pagination = response.pagination
        if (success) {
            _data.value = data
            if (isPage && _pagination) {
                pagination.value.currentPage = _pagination.currentPage
                pagination.value.pageSize = _pagination.pageSize
                pagination.value.total = _pagination.total
            }
        } else {
            _data.value = []
            pagination.value.total = 0
            ElMessage.error(msg)
        }
        loading.value = false
    }

    function handleSelectionChange(rows) {
        selection.value = rows
    }

    async function searchEmpty() {
        const {data, success, msg} = await empty()
        if (success) {
            emptyData.value = data
        } else {
            ElMessage.error(msg)
        }
    }
    const instance = getCurrentInstance();
    const _this = instance?.proxy;

    async function handleAdd(formData, ak){
        if (isSub) {
            if (!Array.isArray(_data.value)) {
                _data.value = [formData]
            } else {
                _data.value.push(formData)
            }
            actionsFormVisible.value[ak] = false
            return
        }
        const { success, msg } = await save(formData)
        if (success) {
            await search()
            ElMessage.success(msg)
            actionsFormVisible.value[ak] = false
        } else {
            ElMessage.error(msg)
        }
    }

    async function handleEdit(formData, ak){
        if (isSub) {
            if (!_data.value) {
                _data.value = []
            }
            if (ak.startsWith('row')) {
                const $index = ak.replace('row', '').split('_')[0]
                _data.value[$index] = formData
            } else {
                //todo 估计会有问题
                selection.value = formData
            }
            actionsFormVisible.value[ak] = false
            return
        }
        const { success, msg } = await update(formData)
        if (success) {
            await search()
            ElMessage.success(msg)
            actionsFormVisible.value[ak] = false
        } else {
            ElMessage.error(msg)
        }
    }

    async function handleDelete(selection){
        if (isSub) {
            if (!_data.value) {
                _data.value = []
            }
            _data.value = _data.value.filter(item => !selection.includes(item))
            return
        }
        if (!selection || !selection.length) {
            ElMessage.warning('请选择要删除的数据')
            return
        }
        const { success, msg } = await removeByIds(selection.map(item => item.id))
        if (success) {
            await search()
            ElMessage.success(msg)
        } else {
            ElMessage.error(msg)
        }
    }

    async function handleImportTemplate(excelOption) {
        const option = {
            columns: columns.value,
            fileName: excelOption.fileName || `${simpleTitle}导入模板.xlsx`,
            sheet: excelOption.sheet || simpleTitle,
        }
        if (excelOption.columns && excelOption.columns.length) {
            option.columns = excelOption.columns
        }
        option.columns = option.columns.filter(item => item.type !== 'selection' && item.type !== 'index')
        await importTemplate(option)
    }

    async function handleImportData(excelOption, ak) {
        const option = {
            columns: columns.value,
            file: excelOption.file,
            sheet: excelOption.sheet || simpleTitle,
        }
        if (excelOption.columns && excelOption.columns.length) {
            option.columns = excelOption.columns
        }
        option.columns = option.columns.filter(item => item.type !== 'selection' && item.type !== 'index')
        const { success, msg } = await importData(option)
        if (success) {
            ElMessage.success(msg)
            actionsFormVisible.value[ak] = false
            await search()
        } else {
            ElMessage.error(msg)
            await search()
        }
    }

    function computeColumnWidth(field) {
        return 18 * Math.max(field.length, _data.value.reduce((max, item) => item[field] && item[field].length > max ? item[field].length : max, 0))
    }

    return {
        commonQueryFn,
        ...commonQueryFn,
        baseUrl,
        rowForm,
        _data,
        queryParams,
        selection,
        getQueryOptions,
        orderBy,
        isPage,
        pagination,
        emptyData,
        _this,
        loading,
        search,
        searchEmpty,
        handleSelectionChange,
        handleAdd,
        handleEdit,
        handleDelete,
        handleImportTemplate,
        handleImportData,
        computeColumnWidth,
        actionsFormVisible,
        isSub,
    }
}


export {commonHook}

